package cn.cdeden.knowledge.controller.recycle.factory;

import cn.cdeden.common.core.domain.R;
import cn.cdeden.common.core.utils.MapstructUtils;
import cn.cdeden.common.core.utils.MessageUtils;
import cn.cdeden.common.core.utils.page.TableDataInfo;
import cn.cdeden.common.mybatis.validator.QueryHelpMybatisPlus;
import cn.cdeden.common.satoken.utils.LoginHelper;
import cn.cdeden.knowledge.domain.FilesTreeRecycle;
import cn.cdeden.knowledge.domain.Team;
import cn.cdeden.knowledge.domain.TeamFilesTree;
import cn.cdeden.knowledge.domain.TeamRelevanceRole;
import cn.cdeden.knowledge.domain.dto.*;
import cn.cdeden.knowledge.domain.enums.MessageTypeEnums;
import cn.cdeden.knowledge.domain.vo.FilesTreeRecycleVo;
import cn.cdeden.knowledge.enums.*;
import cn.cdeden.knowledge.mapper.TeamFilesTreeMapper;
import cn.cdeden.knowledge.mapper.TeamMapper;
import cn.cdeden.knowledge.service.*;
import cn.cdeden.knowledge.utils.DateUtil;
import cn.cdeden.system.api.model.LoginUser;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @ProjectName : ecm_hou
 * @Package : com.cdyd.ecm.file.recycle.factory
 * @ClassName : RecyclePersonal
 * @Author : Yu.
 * @Description : // 团队文档 回收站查询
 * @Date : 2022/10/13 14:40
 * @Version : 1.0
 */
@RequiredArgsConstructor
@Component("teamRecycle")
public class RecycleTeam implements RecycleInterface {

    private final FilesRecentlyViewedService viewedService;
    private final TeamFilesTreeMapper teamFilesTreeMapper;
    private final TeamFilesTreeService teamFilesTreeService;
    private final TeamMemberService teamMemberService;
    private final TeamRelevanceRoleService teamRelevanceRoleService;
    private final FilesCollectionService filesCollectionService;
    private final TeamMapper teamMapper;
    private final FilesLabelRecordService filesLabelRecordService;
    private final FilesAttentionService filesAttentionService;
    private final FilesTreeService filesTreeService;
    private final SysMessageService messageService;
    private final SysDocLogService sysDocLogService;

    private final SysFormDocService sysFormDocService;


    @Override
    public TableDataInfo<FilesTreeRecycleVo> selectRecycleAll(FilesTreeRecycleParam query, Pageable pageable) {
//        List<String> sortDesc = query.getSortDesc();
//        List<String> sortAsc = query.getSortAsc();
//        if (CollectionUtils.isEmpty(sortDesc) && CollectionUtils.isEmpty(sortAsc)) {
//            sortDesc = new ArrayList<>();
//            sortDesc.add("delete_time");
//        }
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<String> sort = new ArrayList<>();
        sort.add("delete_time DESC");

        if (!teamMemberService.checkPermission(query.getTeamId(), loginUser, TeamParamEnum.CHECK.getParam())) {
            throw new RuntimeException("不是团队成员，无权限查看");
        }

        List<TeamRelevanceRole> relevanceRole = teamRelevanceRoleService.getRelevanceRole(query.getTeamId(), loginUser.getUserId(), null);
        List<TeamFilesTree> teamFilesTrees = teamFilesTreeMapper.selectListTreePage(null, query.getRealName(), query.getTeamId(), relevanceRole, pageable.getPageNumber() * pageable.getPageSize(), pageable.getPageSize(), false, query.getAsc(), query.getDesc(), sort, "1");
        int count = teamFilesTreeMapper.selectListTreePageCount(null, query.getRealName(), false, query.getTeamId(), relevanceRole);
        List<TeamFilesTreeDto> teamFilesTreeDtos = MapstructUtils.convert(teamFilesTrees, TeamFilesTreeDto.class);
        TableDataInfo<TeamFilesTreeDto> teamFilesTreeDtoPageInfo = new TableDataInfo<>();
        teamFilesTreeDtoPageInfo.setRows(teamFilesTreeDtos);
        teamFilesTreeDtoPageInfo.setPageSize(pageable.getPageSize());
        teamFilesTreeDtoPageInfo.setPage(pageable.getPageNumber());
        teamFilesTreeDtoPageInfo.setTotal(count);
        List<FilesTreeRecycleVo> treeVoList = MapstructUtils.convert(teamFilesTrees, FilesTreeRecycleVo.class);
        for (FilesTreeRecycleVo filesTreeRecycleVo : treeVoList) {
            Team team = teamMapper.selectById(filesTreeRecycleVo.getTeamId());
            filesTreeRecycleVo.setHeadNodeId(team.getHeadNodeId());
        }
        return MapstructUtils.convertTableDataInfo(teamFilesTreeDtoPageInfo, FilesTreeRecycleVo.class);
    }

    @Override
    public boolean deleteBatch(List<String> ids, String jsonObject) {
//        if (jsonObject == null) {
        LoginUser user = LoginHelper.getLoginUser();
//        } else {
//            user = JSONObject.parseObject(jsonObject, FileUserDto.class);
//        }
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        List<TeamFilesTree> treeList = teamFilesTreeService.listByIds(ids);

        if (CollectionUtils.isEmpty(treeList)) {
            throw new RuntimeException("错误的信息删除");
        } else {
            treeList.forEach(filesTree -> {

                TeamQueryParam teamQueryParam = new TeamQueryParam();
                QueryWrapper<Team> predicate2 = QueryHelpMybatisPlus.getPredicate(teamQueryParam);
                predicate2.eq("id", filesTree.getTeamId());

                //团队角色权限
                if (!teamRelevanceRoleService.checkPermission(String.valueOf(filesTree.getId()), filesTree.getTeamId(), LoginHelper.getLoginUser(), TeamParamEnum.DELETE.getParam())) {
                    throw new RuntimeException("无删除权限，请联系管理员");
                }
            });
            Set<String> setIds = new HashSet<>();
            setIds.addAll(deleteBatch(ids, userId, username));
            setIds.addAll(ids);
            Long sizeCount = 0L;
            String parentId = null;
            for (String id : ids) {
                TeamFilesTree teamFilesTree = teamFilesTreeService.getById(id);
                parentId = teamFilesTree.getParentId();
                if (teamFilesTree.getSize() != null) {
                    sizeCount = teamFilesTree.getSize() + sizeCount;
                }
            }
            if (sizeCount != 0L)
                teamFilesTreeService.setParentNodeSize(parentId, sizeCount, 1);

            List<String> list = new ArrayList<>(setIds);
            for (String s : list) {
                //添加到日志中心团队文档
                TeamFilesTree teamFilesTree = teamFilesTreeService.getById(s);
                sysDocLogService.createLog(String.valueOf(teamFilesTree.getId()), null, TreeEnum.TEAM, OperationEnum.DELETE.judgmentType(teamFilesTree.getType()), teamFilesTree.getRealName(), teamFilesTree.getPath(), DeleteTypeEnums.DISPLAY.getType());
            }
            try {
                filesCollectionService.deleteLibTaggedData("1", list);
                filesLabelRecordService.deleteByFileIds(setIds, TreeEnum.TEAM.getType());
                viewedService.deleteByIds(new HashSet<>(list), TreeEnum.TEAM.getType());
            } catch (Exception e) {
                System.err.println("============================================================");
                e.printStackTrace();
            }

            UpdateWrapper<TeamFilesTree> updateWrapper = new UpdateWrapper<TeamFilesTree>()
                .set("delete_id", userId).set("delete_by", username)
                .set("delete_type", DeleteTypeEnums.DISPLAY.getType())
                .set("delete_time", new Date())
                .in("id", ids);


            for (String setId : setIds) {
                TeamFilesTree teamFilesTree = teamFilesTreeService.getById(setId);
                List<TreeNodeDto> parentTreeNodeAll = null;
                try {
                    parentTreeNodeAll = filesTreeService.getParentTreeNodeAll(String.valueOf(teamFilesTree.getId()), "1");
                } catch (BadRequestException e) {
                    throw new RuntimeException(e);
                }
                for (TreeNodeDto treeNodeDto : parentTreeNodeAll) {
                    String id = treeNodeDto.getId();
                    List<String> attentionPeople = filesAttentionService.getAttentionPeople(id, "1");
                    for (String attentionPerson : attentionPeople) {
                        //创建消息
                        SysMessageDto sysMessageDto = new SysMessageDto();
                        sysMessageDto.setContent("您关注的: “" + treeNodeDto.getRealName() + "”  “" + teamFilesTree.getRealName() + "”被删除了。 操作人：" + user.getNickname());
                        sysMessageDto.setOperator(LoginHelper.getUserId().toString());
                        sysMessageDto.setNodeId(String.valueOf(teamFilesTree.getId()));
                        sysMessageDto.setMessageType("0");
                        sysMessageDto.setType(MessageTypeEnums.ADD.getCode());
                        sysMessageDto.setFileType(MessageFileTypeEnums.TEAM.getCode());
                        sysMessageDto.setRecipient(attentionPerson);
                        sysMessageDto.setTeamId(String.valueOf(teamFilesTree.getTeamId()));
                        messageService.addMessage(sysMessageDto);
                    }
                }
            }

            return teamFilesTreeService.update(updateWrapper);
//            return true;
        }
    }

    @Override
    public List<FilesTreeRecycle> deleteRecycle(List<String> ids, String type, String teamId) {

        //团队角色权限
        if (!teamMemberService.checkPermission(teamId, LoginHelper.getLoginUser(), TeamParamEnum.RECYCLE.getParam())) {
            throw new RuntimeException("无回收站操作权限，请联系管理员");
        }

        List<FilesTreeRecycle> recycleList = null;
        if (StringUtils.equalsIgnoreCase("0", type)) {
            if (CollectionUtils.isEmpty(ids)) {
                throw new RuntimeException("删除数据为空");
            }
            recycleList = deleteRecycle(ids, teamId);
        } else if (StringUtils.equalsIgnoreCase("1", type)) {
            recycleList = deleteRecycleAll(teamId);
        }
        Team team = teamMapper.selectById(teamId);
        Long ListSpace = 0L;
        recycleList.forEach(FilesTreeRecycle::getFileTreeId);

        for (FilesTreeRecycle filesTreeRecycle : recycleList) {
            if (!filesTreeRecycle.getType().equals(TreeTypeEnum.FOLDER.getType()))
                ListSpace = ListSpace + filesTreeRecycle.getSize(); //只计算文件的大小
            sysDocLogService.createLog(String.valueOf(filesTreeRecycle.getFileTreeId()), null, TreeEnum.TEAM, OperationEnum.DELETE.judgmentType(filesTreeRecycle.getType()), filesTreeRecycle.getRealName(), filesTreeRecycle.getPath(), DeleteTypeEnums.NO_DISPLAY.getType());
        }
        team.setUsedSpace(team.getUsedSpace() - ListSpace);
        teamMapper.updateById(team);
        //删除数据
        if (CollectionUtils.isEmpty(recycleList)) {
            throw new RuntimeException("删除数据为空");
        }
        List<Long> longs = recycleList.stream().map(FilesTreeRecycle::getFileTreeId).collect(Collectors.toList());
        boolean b = teamFilesTreeService.removeByIds(longs);

        return recycleList;
    }

//    @Override
//    public List<FilesTreeRecycle> recoverTiming(Date date) {
//        List<FilesTreeRecycle> recycleList = deleteRecycle(date);
//        //删除数据
//        if (CollectionUtils.isEmpty(recycleList)) {
//            return null;
//        }
//        List<Long> longs = recycleList.stream().map(FilesTreeRecycle::getFileTreeId).collect(Collectors.toList());
//        boolean b = teamFilesTreeService.removeByIds(longs);
//
//        return recycleList;
//    }

    private List<FilesTreeRecycle> deleteRecycle(Date date) {
        String dateStr = DateUtil.localDateTimeFormat(DateUtil.toLocalDateTime(date), DateUtil.DFY_MD);
        LambdaQueryWrapper<TeamFilesTree> wrapper = new LambdaQueryWrapper<TeamFilesTree>()
            .eq(TeamFilesTree::getDeleteType, DeleteTypeEnums.DISPLAY.getType())
            .lt(TeamFilesTree::getDeleteTime, dateStr);

        List<TeamFilesTree> treeList = teamFilesTreeService.list(wrapper);

        if (CollectionUtils.isEmpty(treeList)) {
            return null;
        }
        return deleteRecycleActual(null, treeList);
    }


    private Set<String> deleteBatch(List<String> ids, String userId, String username) {
        QueryWrapper<TeamFilesTree> queryWrapper = new QueryWrapper<TeamFilesTree>().in("parent_id", ids).isNull("delete_id");
        List<TeamFilesTree> list = teamFilesTreeService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            Set<String> setId = new HashSet<>();
            List<String> list1 = new ArrayList<>();
            list.forEach(tree -> {
                String of = String.valueOf(tree.getId());
                setId.add(of);
                if (StringUtils.equalsIgnoreCase(TreeTypeEnum.FOLDER.getType(), tree.getType())) {
                    list1.add(of);
                }
//                //修改上级文件大小
//                TeamFilesTree teamFilesTree = teamFilesTreeService.getById(tree.getParentId());
//                if (tree.getSize() != null){
//                    teamFilesTree.setSize(teamFilesTree.getSize()-tree.getSize());
//                }
//                teamFilesTreeService.updateById(teamFilesTree);
            });
            folderCheck(list1, setId, true);
//            throw new RuntimeException()("选中的文件夹中有子级，无法删除");
//            setId.forEach(System.out::println);

            UpdateWrapper<TeamFilesTree> updateWrapper = new UpdateWrapper<TeamFilesTree>()
                .set("delete_id", userId).set("delete_by", username)
                .set("delete_type", DeleteTypeEnums.DISPLAY.getType())
                .set("delete_time", new Date())
                .in("id", setId);
            teamFilesTreeService.update(updateWrapper);
            return setId;
        }
        return new HashSet<>();
    }

    /**
     * @param ids
     * @param setId
     * @param b
     * @return void
     * @author Yu.
     * @Description // 文件下的所有文件
     * @Date 2022/10/14 15:51
     **/
    private void folderCheck(List<String> ids, Set<String> setId, boolean b) {
        if (CollectionUtils.isEmpty(ids) || ids.size() <= 0) {
            return;
        }
//        ArrayList<String> ids = new ArrayList<>(setId);
        QueryWrapper<TeamFilesTree> queryWrapper = new QueryWrapper<TeamFilesTree>().in("parent_id", ids);
        if (b) {
            queryWrapper.isNull("delete_id");
        } else {
            queryWrapper.isNotNull("delete_id").eq("delete_type", "2");
        }
        List<TeamFilesTree> list = teamFilesTreeService.list(queryWrapper);
        if (CollectionUtils.isNotEmpty(list)) {
            List<String> list1 = new ArrayList<>();
            list.forEach(tree -> {
                if (StringUtils.equalsIgnoreCase(TreeTypeEnum.FOLDER.getType(), tree.getType())) {
                    list1.add(String.valueOf(tree.getId()));
                }
                setId.add(String.valueOf(tree.getId()));
            });
            folderCheck(list1, setId, b);
//            throw new RuntimeException()("选中的文件夹中有子级，无法删除");
        }
    }


    @Override
    public R recoverFileList(List<String> ids, String teamId) {

        //团队角色权限
        if (!teamMemberService.checkPermission(teamId, LoginHelper.getLoginUser(), TeamParamEnum.RECYCLE.getParam())) {
            return R.fail(ResultEnum.PERM_ERROR.getNum(), "无回收站操作权限，请联系管理员");
        }

        if (ids.size() > 1) {
            return recoverFile(ids);
        } else {
            return recoverFile(ids.get(0));
        }
    }

    public R recoverFile(String id) {
        LoginUser user = LoginHelper.getLoginUser(); //用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        QueryWrapper<TeamFilesTree> queryWrapper = new QueryWrapper<TeamFilesTree>();
        queryWrapper.eq("id", id).isNotNull("delete_id");
        TeamFilesTree filesTree = teamFilesTreeService.getOne(queryWrapper);

        QueryWrapper<TeamFilesTree> wrapper = new QueryWrapper<TeamFilesTree>()
            .eq("id", filesTree.getParentId()).isNull("delete_id");

        TeamFilesTree personalFile = teamFilesTreeService.getOne(wrapper);
        if (ObjectUtils.isEmpty(personalFile)) {
            return R.ok(null, "请选择还有位置");
        }
        boolean b = recoverFile(filesTree, userId, username);
        return R.ok(null, "还原成功");
    }

    public R recoverFile(List<String> ids) {
        LoginUser user = LoginHelper.getLoginUser(); //用户信息
        String username = user.getUsername();
        String userId = Long.toString(user.getUserId());
        QueryWrapper<TeamFilesTree> queryWrapper = new QueryWrapper<TeamFilesTree>();
        queryWrapper.in("id", ids).eq("create_id", userId).isNotNull("delete_id");
        List<TeamFilesTree> filesTrees = teamFilesTreeService.list(queryWrapper);
        if (CollectionUtils.isEmpty(filesTrees) && filesTrees.size() != ids.size()) {
            throw new RuntimeException("错误的 有错误的 文件序号");
        }
        List<TeamFilesTree> success = new ArrayList<>();
        List<TeamFilesTree> exception = new ArrayList<>();
        // 循环恢复数据
        filesTrees.forEach(file -> {
            boolean b = recoverFile(file, userId, username);
            if (b) {
                success.add(file);
            } else {
                exception.add(file);
            }
        });

        if (CollectionUtils.isNotEmpty(exception) && exception.size() > 0) {
            StringBuilder message = new StringBuilder(success.size() + "个对象还原成功,");
            StringJoiner joiner = new StringJoiner(",");
            exception.forEach(tree -> {
                joiner.add(tree.getRealName());
            });
            message.append(joiner);
            message.append("等");
            message.append(exception.size());
            message.append("个对象的原目录文件夹已不存在，请单独进行还原");
            return R.ok(null, message.toString());
        } else {
            return R.ok(null, "还原成功");
        }
    }

    public boolean recoverFile(TeamFilesTree filesTree, String userId, String username) {
//        //判断团队是否被删除 如果被删除 先恢复团队
//        String teamId = filesTree.getTeamId();
//        Team team = teamMapper.selectById(teamId);
//        if (team.getDeleteId() != null){
//            team.setDeleteId(null);
//            team.setDeleteBy(null);
//            team.setDeleteTime(null);
//            teamMapper.updateById(team);
//        }
        QueryWrapper<TeamFilesTree> queryWrapper = new QueryWrapper<TeamFilesTree>()
            .eq("id", filesTree.getParentId()).isNull("delete_id");

        TeamFilesTree teamFilesTree = teamFilesTreeService.getOne(queryWrapper);
        if (ObjectUtils.isEmpty(teamFilesTree)) {
            return false;
        }
        String realName = filesTree.getRealName();
        String id = Long.toString(filesTree.getId());
        if (teamFilesTreeService.nameRechecking(realName, String.valueOf(filesTree.getParentId()), filesTree.getSuffix()) != null) {
            realName += "_" + System.currentTimeMillis();
        }
        //修改上级文件大小
        if (filesTree.getSize() != null) {
            teamFilesTree.setSize(teamFilesTree.getSize() + filesTree.getSize());
        }
        teamFilesTreeService.updateById(teamFilesTree);

        //看是否是文件夹 下是否要恢复文件
        if (StringUtils.equalsIgnoreCase(TreeTypeEnum.FOLDER.getType(), filesTree.getType())) {
            recoverFile(Long.toString(filesTree.getId()), userId, username);
        }

        UpdateWrapper<TeamFilesTree> updateWrapper = new UpdateWrapper<TeamFilesTree>()
            .set("delete_id", null).set("delete_by", null)
            .set("delete_time", null)
            .set("delete_type", null)
            .set("real_name", realName)
            .set("update_id", userId).set("update_by", username).set("update_time", new Date())
            .eq("id", filesTree.getId());

        sysDocLogService.createLog(String.valueOf(filesTree.getId()), null, TreeEnum.TEAM, OperationEnum.RECOVER.judgmentType(filesTree.getType()), filesTree.getRealName(), filesTree.getPath(), null);
        return teamFilesTreeService.update(updateWrapper);
    }

    public boolean recoverFile(String id, String userId, String username) {
        QueryWrapper<TeamFilesTree> queryWrapper = new QueryWrapper<TeamFilesTree>()
            .eq("parent_id", id).isNotNull("delete_id").eq("delete_type", "2");
        List<TeamFilesTree> treeList = teamFilesTreeService.list(queryWrapper);
        if (CollectionUtils.isEmpty(treeList)) {
            return true;
        }

        Set<String> ids = new HashSet<>();
        List<String> idList = new ArrayList<>();
        treeList.forEach(tree -> {
            String of = String.valueOf(tree.getId());
            if (StringUtils.equalsIgnoreCase(TreeTypeEnum.FOLDER.getType(), tree.getType())) {
                idList.add(of);
            }
            ids.add(of);
        });

        //查找需要修改文件的
        folderCheck(idList, ids, false);

        UpdateWrapper<TeamFilesTree> updateWrapper = new UpdateWrapper<TeamFilesTree>()
            .set("delete_id", null).set("delete_by", null)
            .set("delete_time", null)
            .set("delete_type", null)
            .set("update_id", userId).set("update_by", username).set("update_time", new Date())
            .in("id", ids);
        return teamFilesTreeService.update(updateWrapper);
    }


//    @Override
//    public R recoverFileChooseAPath(RecycleRecoverFileChooseAPath path) {
//        String id = path.getId();
//        String parentId = path.getParentId();
//
//        LoginUser user = LoginHelper.getLoginUser(); //用户信息
//        String username = user.getUsername();
//        String userId = Long.toString(user.getUserId());
//        QueryWrapper<TeamFilesTree> queryWrapper = new QueryWrapper<TeamFilesTree>();
//        queryWrapper.eq("id", id).eq("create_id", userId).isNotNull("delete_id");
//        TeamFilesTree filesTree = teamFilesTreeService.getOne(queryWrapper);
//
//
//        QueryWrapper<TeamFilesTree> wrapper = new QueryWrapper<TeamFilesTree>()
//                .eq("id", parentId).isNull("delete_id");
//
//        TeamFilesTree personalFile = teamFilesTreeService.getOne(wrapper);
//        if (ObjectUtils.isEmpty(personalFile)) {
//            return R.ok(null, RespResultEnums.HINT_OPERATION, "请选择没有删除的父节点");
//        }
//
//        String realName = filesTree.getRealName();
////        String id = Long.toString(filesTree.getId());
//        if (teamFilesTreeService.nameRechecking(realName, filesTree.getParentId(), filesTree.getSuffix()) != null) {
//            realName += "_" + System.currentTimeMillis();
//        }
//        String treePath = filesTree.getPath();
//        String filePath = personalFile.getPath();
//        String pathName = filePath + "/" + realName;
//        UpdateWrapper<TeamFilesTree> updateWrapper = new UpdateWrapper<TeamFilesTree>()
//                .set("delete_id", null).set("delete_by", null).set("delete_time", null).set("delete_type", null)
//                .set("parent_id", parentId)
//                .set("superiors_path", filePath)
//                .set("path", pathName)
//                .set("real_name", realName)
//                .set("update_id", userId).set("update_by", username).set("update_time", new Date())
//                .eq("id", filesTree.getId());
//        teamFilesTreeService.update(updateWrapper);
//
//
//        UpdateWrapper<TeamFilesTree> update = new UpdateWrapper<>();
//        int length = treePath.length();
//        update.setSql("path=INSERT(path,1," + length + ",'" + pathName + "')")
//                .setSql("superiors_path=INSERT(superiors_path,1," + length + ",'" + pathName + "')")
//                .set("delete_id", null).set("delete_by", null).set("delete_time", null).set("delete_type", null)
//                .set("update_id", userId).set("update_by", username).set("update_time", new Date())
//                .likeRight("path", treePath)
//                .ne("id", id).isNotNull("delete_id");
//        teamFilesTreeService.update(update);
//
//        return R.ok(null, "还原成功");
//    }

//    @Override
//    public R foxBaseRecoverFileChooseAPath(List<FilesTreeRecycle> recycleList) {
//        try {
//            LoginUser user = LoginHelper.getLoginUser(); //用户信息
//            String username = user.getUsername();
//            String userId = Long.toString(user.getUserId());
//            List<TeamFilesTree> filesTrees = new ArrayList<>();
//            recycleList.forEach(tree -> {
////            getFileTree(tree)
////            filesTrees.add();
//                String parentId = tree.getParentId();
//                TeamFilesTree byId = teamFilesTreeService.getById(parentId);
//                if (ObjectUtils.isEmpty(byId)) {
//                    throw new RuntimeException();
//                }
//                TeamFilesTree filesTree = MapstructUtils.convert(tree, TeamFilesTree.class);
//                filesTree.setId(tree.getFileTreeId());
//                filesTree.setSuperiorsPath(byId.getPath());
//                filesTree.setDeleteBy(null);
//                filesTree.setDeleteType(null);
//                filesTree.setDeleteTime(null);
//                filesTree.setDeleteId(null);
//
//                filesTree.setUpdateTime(new Date());
//                filesTree.setUpdateId(userId);
//                filesTree.setUpdateBy(username);
//
//
//                //是否重命名处理
//                TeamFilesTree teamFilesTree = teamFilesTreeService.nameRechecking(filesTree.getRealName(), parentId, filesTree.getSuffix());
//                if (teamFilesTree != null) {
//                    filesTree.setRealName(filesTree.getRealName() + "_恢复_" + System.currentTimeMillis());
//                } else {
//                    filesTree.setRealName(filesTree.getRealName() + "_恢复");
//                }
//                filesTree.setPath(byId.getPath() + "/" + filesTree.getRealName());
//                //
//                filesTrees.add(filesTree);
//
//                if (StringUtils.equalsIgnoreCase(tree.getType(), TreeTypeEnum.FOLDER.getType())) {
//                    List<FilesTreeRecycle> list = tree.getSonDataList();
//                    if (CollectionUtils.isNotEmpty(list)) {
//                        list.forEach(recycle1 -> {
//                            List<TeamFilesTree> fileTree = getFileTree(recycle1, filesTree.getPath(), userId, username);
//                            filesTrees.addAll(fileTree);
//                        });
//                    }
//                }
//                sysDocLogService.createLog(String.valueOf(tree.getFileTreeId()), null, TreeEnum.TEAM, OperationEnum.RECOVER.judgmentType(tree.getType()), tree.getRealName(), tree.getPath(), null);
//            });
//            if (CollectionUtils.isEmpty(filesTrees)) {
//                throw new RuntimeException();
//            }
//
//            return R.ok(teamFilesTreeService.saveBatch(filesTrees));
//        } catch (Exception e) {
//            return R.fail("还原失败：" + e);
//        }
//
//    }

//    private List<TeamFilesTree> getFileTree(FilesTreeRecycle recycle, String superiorsPath, String userId, String username) {
//        List<TeamFilesTree> filesTrees = new ArrayList<>();
//        TeamFilesTree tree = MapstructUtils.convert(recycle, TeamFilesTree.class);
//        tree.setId(recycle.getFileTreeId());
//        tree.setSuperiorsPath(superiorsPath);
//        tree.setPath(superiorsPath + "/" + tree.getRealName());
//
//        tree.setDeleteBy(null);
//        tree.setDeleteType(null);
//        tree.setDeleteTime(null);
//        tree.setDeleteId(null);
//
//        tree.setUpdateTime(new Date());
//        tree.setUpdateId(userId);
//        tree.setUpdateBy(username);
//
//
//        filesTrees.add(tree);
//        if (StringUtils.equalsIgnoreCase(tree.getType(), TreeTypeEnum.FOLDER.getType())) {
//            List<FilesTreeRecycle> list = recycle.getSonDataList();
//            if (CollectionUtils.isNotEmpty(list)) {
//
//                list.forEach(recycle1 -> {
//                    List<TeamFilesTree> fileTree = getFileTree(recycle1, tree.getPath(), userId, username);
//                    filesTrees.addAll(fileTree);
//                });
////                tree.setSonDataList(filesTrees);
//            }
//        }
//        return filesTrees;
//    }


    private List<FilesTreeRecycle> deleteRecycle(List<String> ids, String teamId) {
        LoginUser user = LoginHelper.getLoginUser(); //用户信息
        String userId = Long.toString(user.getUserId());

        if (CollectionUtils.isEmpty(ids)) {
            throw new RuntimeException("错误的 删除对象");
        }

        QueryWrapper<TeamFilesTree> wrapper = new QueryWrapper<TeamFilesTree>()
            .eq("team_id", teamId)
            .eq("delete_type", "1")
            .ne("type", "head")
            .in("id", ids);
        List<TeamFilesTree> treeList = teamFilesTreeService.list(wrapper);
        if (CollectionUtils.isEmpty(treeList)) {
            throw new RuntimeException("没有要删除的对象");
        }
        return deleteRecycleActual(userId, treeList);
    }

    private List<FilesTreeRecycle> deleteRecycleActual(String userId, List<TeamFilesTree> treeList) {
        List<FilesTreeRecycle> recycleList = new ArrayList<>();
        List<String> ids = new ArrayList<>();
        treeList.forEach(tree -> {
            FilesTreeRecycle recycle = FilesTreeRecycle.getTeamRecycle(tree);
            if (StringUtils.equalsIgnoreCase(tree.getType(), TreeTypeEnum.FOLDER.getType())) {
//                ids.add(Long.toString(tree.getId()));
                Long treeId = recycle.getFileTreeId();
//                recycleList.add
            } else if (StringUtils.equalsIgnoreCase(tree.getType(), TreeTypeEnum.RICHTEXT.getType())) {
                //删除富文本文档
                sysFormDocService.deleteByTreeNodeId(String.valueOf(tree.getId()), "1");
            }
            recycleList.add(recycle);
        });

//        //删除 文件树
//        filesTreeService.removeByIds(ids);
//
//        //删除 实际文件
//        if (CollectionUtils.isNotEmpty(fileList)) {
//            List<String> fileIds = new ArrayList<>();
//            List<String> Ids = new ArrayList<>();
//            fileList.forEach(tree -> {
//                fileIds.add(tree.getStorageId());
//                Ids.add(Long.toString(tree.getId()));
//            });
//            fileStorageUtils.deleteBatch(fileIds);
//            filesTreeService.removeByIds(Ids);
//        }
        return recycleList;
    }

    private List<FilesTreeRecycle> deleteRecycleAll(String teamId) {
        LoginUser user = LoginHelper.getLoginUser(); //用户信息
        String userId = Long.toString(user.getUserId());
        QueryWrapper<TeamFilesTree> wrapper = new QueryWrapper<TeamFilesTree>()
            .eq("team_id", teamId)
            .eq("delete_type", "1")
            .ne("type", "head");
        List<TeamFilesTree> treeList = teamFilesTreeService.list(wrapper);
        if (CollectionUtils.isEmpty(treeList)) {
            throw new RuntimeException("没有要删除的对象");
        }
        return deleteRecycleActual(userId, treeList);
    }

}
